<script setup lang="ts">
import ListSearch from './ListSearch.vue'
import { computed, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { refreshFriendApply } from '../api/cache'

const emit = defineEmits(['show-friend-view', 'show-friend-apply-list', 'show-friend-search-view'])
const store = useStore()
const friendList = computed(() => store.getters.getFriendList)
const props = defineProps({
  friendApplyNotification: Boolean
})

onMounted(() => {
  addFriendListStyle()
})

watch(friendList, () => {
  addFriendListStyle()
  if (document.querySelector('.friend-list')) {
    document.querySelector('.friend-list')!.classList.add('bg-gray-300')
  }
})

const showFriendApplyList = () => {
  emit('show-friend-apply-list')
  refreshFriendApply(store.getters.getUserId)
}

const showFriendView = (userId: number) => emit('show-friend-view', userId)

const showFriendSearchView = () => {
  emit('show-friend-search-view')
  document.querySelectorAll('.friend-list').forEach((allItem) => {
    allItem.classList.remove('bg-gray-300')
  })
}

const addFriendListStyle = () => {
  document.querySelectorAll('.friend-list').forEach((item) => {
    item.addEventListener('click', function () {
      document.querySelectorAll('.friend-list').forEach((allItem) => {
        allItem.classList.remove('bg-gray-300')
      })
      item.classList.add('bg-gray-300')
    })
  })
}
</script>

<template>
  <div class="h-full flex flex-col divide-y divide-slate-300">
    <list-search has-add-btn add-btn-method="friend" @friend-search-view="showFriendSearchView" />

    <div class="w-full overflow-y-auto" style="height: 636px">
      <ul class="flex flex-col h-full w-full list-none">
        <li
          class="flex w-full pt-2 pl-2 pr-2 pb-2 hover:cursor-pointer hover:bg-gray-300 friend-list"
          @click="showFriendApplyList"
        >
          <img
            src="../assets/friendApply.png"
            alt="Avatar"
            class="w-10 h-10 rounded-full object-scale-down mr-3"
          />
          <div class="flex flex-col justify-center items-start w-full">
            <div class="mb-1">
              <p class="font-semibold text-sm">好友申请</p>
            </div>
          </div>
          <el-badge class="m-auto" :is-dot="props.friendApplyNotification"></el-badge>
        </li>
        <li
          v-for="(item, key) in friendList"
          :key="key"
          class="flex w-full pt-2 pl-2 pr-2 pb-2 hover:cursor-pointer hover:bg-gray-300 friend-list"
          @click="showFriendView(item.userId)"
        >
          <img
            :src="item.avatar"
            alt="Avatar"
            class="w-10 h-10 rounded-full object-scale-down mr-3"
          />
          <div class="flex flex-col justify-center items-start w-full">
            <div class="mb-1">
              <p class="font-semibold text-sm">{{ item.nickname }}</p>
            </div>
          </div>
        </li>
      </ul>
    </div>
  </div>
</template>

<style scoped></style>
